import os.path
from os import abort
import uuid
from sqlalchemy.testing.suite.test_reflection import users
from app.exts import db
from flask import Blueprint, render_template, request, session, jsonify, redirect,url_for,current_app,flash,g

from werkzeug.utils import secure_filename

from .blog import categories
from .forms import BlogForm
from app.models import *
from ..decorators import login_required

bp=Blueprint('security',__name__,url_prefix='/end',template_folder='../templates/end')

@bp.route('/')
def test():
    return render_template('endbase.html')
@bp.route('/detail')
def detail():
    return '后台页面设计中……'
@bp.route('/writeBlog', methods=['GET', 'POST'])
@login_required
def write_blog():
    def process_tags(blog, tag_names):
        blog.tags.clear()
        for tag_name in tag_names:
            tag = TagModel.query.filter_by(name=tag_name).first()
            if not tag:
                tag = TagModel(name=tag_name)
                db.session.add(tag)
            blog.tags.append(tag)

    if request.method == 'GET':
        categories = CategoriesModel.query.all()
        return render_template('writeblog.html', categories=categories)
    else:
        form = BlogForm(request.form)
        if form.validate():
            blog_id = request.form.get('blog_id')
            title = form.title.data
            content = form.content.data
            categorie_id = form.categorie_id.data
            tags_str = form.tags.data
            author_id = form.author_id.data
            status = request.form.get('status')
            picture_path = None
            file = request.files.get('picture')
            try:
                if file and file.filename:
                    filename = secure_filename(file.filename)
                    file_path = os.path.join(current_app.config['COVER_FOLDER'], filename)
                    file.save(file_path)
                    picture_path = f"uploads/covers/{filename}"
                    if blog_id:
                        blog = BlogModel.query.get_or_404(blog_id)
                        if blog.picture:
                            old_file_path = os.path.join(current_app.config['COVER_FOLDER'], os.path.basename(blog.picture))
                            if os.path.exists(old_file_path):
                                os.remove(old_file_path)
                tag_names = [t.strip().lower() for t in tags_str.split(' ') if t.strip()]
                if blog_id:
                    blog = BlogModel.query.get_or_404(blog_id)
                    blog.title = title
                    blog.content = content
                    blog.categorie_id = categorie_id
                    blog.status = status
                    if picture_path:
                        blog.picture = picture_path
                    process_tags(blog, tag_names)
                else:
                    blog = BlogModel(
                        title=title,
                        content=content,
                        categorie_id=categorie_id,
                        author_id=author_id,
                        picture=picture_path,
                        status=status
                    )
                    db.session.add(blog)
                    process_tags(blog, tag_names)
                db.session.commit()
                flash('发布成功！', 'success')
                return redirect(url_for('security.write_blog'))
            except Exception as e:
                db.session.rollback()
                flash(f'发布失败！{str(e)}', 'error')
                return redirect(url_for('security.write_blog'))
        else:
            print(form.errors)
            flash('发布失败！' + str(form.errors), 'error')
            return redirect(url_for('security.write_blog'))




ALLOWED_EXTENSIONS = {'jpg', 'jpeg', 'png', 'gif'}


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@bp.route('/upload_image', methods=['POST'])
def upload_image():
    if 'editormd-image-file' not in request.files:
        return jsonify({'success': 0, 'message': 'No file part'})

    file = request.files['editormd-image-file']
    if file.filename == '':
        return jsonify({'success': 0, 'message': 'No selected file'})

    if not allowed_file(file.filename):
        return jsonify({'success': 0, 'message': 'Invalid file type'})

    ext = os.path.splitext(file.filename)[1]
    filename = f"{uuid.uuid4().hex.upper()}{ext}"
    upload_dir = os.path.join(current_app.static_folder, 'uploads', 'covers')
    os.makedirs(upload_dir, exist_ok=True)
    file.save(os.path.join(upload_dir, filename))

    file_url = url_for('static', filename=f'uploads/covers/{filename}')
    return jsonify({'success': 1, 'message': 'Upload success!', 'url': file_url})


@bp.route('/addBlog', methods=['POST'])
@login_required
def add_blog():
    title = request.form.get('title')
    topic_id = request.form.get('topic_id')
    file = request.files.get('cover')
    print('新增中')
    print(title,topic_id,file)
    if not title or not file:
        return jsonify({'error': '标题和封面不能为空'}), 400

    try:
        # 封面图片保存
        filename = secure_filename(file.filename)
        file_path = os.path.join(current_app.config['COVER_FOLDER'], filename)
        file.save(file_path)
        print('封面保存完成')
        picture_path = f"uploads/covers/{filename}"

        # 创建新文章，初始为空内容，status='draft'
        new_blog = BlogModel(
            title=title,
            content='',
            author_id=g.user.id,
            picture=picture_path,
            status='draft',  # 或 '未发布'
            topic_id=topic_id  # 你模型中若有 topic_id 字段
        )
        print('立即新增')
        db.session.add(new_blog)
        db.session.commit()
        print('新增完成')

        return jsonify({'message': '创建成功', 'blog_id': new_blog.id})
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


@bp.route('/addCategory', methods=['GET', 'POST'])
def add_category():
    name = request.form.get('name')
    description = request.form.get('desc')
    cover = request.files.get('cover')

    if not name or not cover:
        return '分类名称和封面不能为空', 400

    if not allowed_file(cover.filename):
        return '上传文件类型不合法', 400

    ext = os.path.splitext(cover.filename)[1]
    filename = f"{uuid.uuid4().hex.upper()}{ext}"
    upload_dir = os.path.join(current_app.static_folder, 'uploads', 'covers')
    os.makedirs(upload_dir, exist_ok=True)
    cover.save(os.path.join(upload_dir, filename))

    cover_path = f"uploads/covers/{filename}"
    category = CategoriesModel(name=name, description=description, cover=cover_path)
    db.session.add(category)
    db.session.commit()

    # return redirect(url_for('security.category_manager'))
    return jsonify({'code': 0, 'message': '添加成功'})


@bp.route('/editCategory/<int:category_id>', methods=['GET', 'POST'])
def edit_category(category_id):
    category = CategoriesModel.query.get_or_404(category_id)
    name = request.form.get('name')
    description = request.form.get('desc')
    cover = request.files.get('cover')

    if not name:
        return jsonify({'code': 1, 'message': '分类名称不能为空'}), 400

    category.name = name
    category.description = description

    if cover and allowed_file(cover.filename):
        ext = os.path.splitext(cover.filename)[1]
        filename = f"{uuid.uuid4().hex.upper()}{ext}"
        upload_dir = os.path.join(current_app.static_folder, 'uploads', 'covers')
        os.makedirs(upload_dir, exist_ok=True)
        cover.save(os.path.join(upload_dir, filename))
        category.cover = f"uploads/covers/{filename}"

    db.session.commit()

    return jsonify({'code': 0, 'message': '编辑成功'})

@bp.route('/initCategoryOrder')
def init_category_order():
    categories=CategoriesModel.query.order_by(CategoriesModel.id).all()
    for index,category in enumerate(categories):
        category.order=index
    db.session.commit()
    return 'success'


@bp.route('/addTopic',methods=['GET','POST'])
def add_topic():
    name=request.form.get('name')
    cover=request.files.get('cover')
    desc=request.form.get('desc')
    if not name or not cover:
        # return '专题名称和封面不能为空',400
        return jsonify({'code': 1, 'message': '专题名称和封面不能为空'}), 400
    if not allowed_file(cover.filename):
        # return '文件类型不合法',400
        return jsonify({'code': 1, 'message': '文件类型不合法'}), 400
    ext=os.path.splitext(cover.filename)[1]
    filename=f"{uuid.uuid4().hex.upper()}{ext}"
    upload_dir=os.path.join(current_app.static_folder,'uploads','covers')
    os.makedirs(upload_dir, exist_ok=True)
    cover.save(os.path.join(upload_dir, filename))
    cover_path=f"uploads/covers/{filename}"

    topic=TopicModel(name=name,cover=cover_path,desc=desc)
    db.session.add(topic)
    db.session.commit()
    return jsonify({'code': 0, 'message': '添加专题成功'})

@bp.route('/editTopic/<int:topic_id>', methods=['GET', 'POST'])
def edit_topic(topic_id):
    topic = TopicModel.query.get_or_404(topic_id)
    name = request.form.get('name')
    desc = request.form.get('desc')
    cover = request.files.get('cover')

    if not name:
        return jsonify({'code': 1, 'message': '分类名称不能为空'}), 400

    topic.name = name
    topic.desc = desc

    if cover and allowed_file(cover.filename):
        ext = os.path.splitext(cover.filename)[1]
        filename = f"{uuid.uuid4().hex.upper()}{ext}"
        upload_dir = os.path.join(current_app.static_folder, 'uploads', 'covers')
        os.makedirs(upload_dir, exist_ok=True)
        cover.save(os.path.join(upload_dir, filename))
        topic.cover = f"uploads/covers/{filename}"
    db.session.commit()

    return jsonify({'code': 0, 'message': '编辑成功'})




@bp.route('/moveCategory/<int:category_id>/<string:direction>',methods=['POST'])
def move_category(category_id,direction):
    category=CategoriesModel.query.get_or_404(category_id)
    if direction not in ['up','down']:
        return 'Invalid direction',400 #格式可能有点问题 maybe json
    if direction=='up':
        neighbor=CategoriesModel.query.filter(CategoriesModel.order < category.order).order_by(CategoriesModel.order.desc()).first()
    else:
        neighbor=CategoriesModel.query.filter(CategoriesModel.order > category.order).order_by(CategoriesModel.order.asc()).first()
    if not neighbor:
        return 'Already at edge',400
    category.order,neighbor.order=neighbor.order,category.order
    db.session.commit()
    return jsonify({'code':0,'message':'移动成功'})



@bp.route('/categoryManager')
def category_manager():
    categories=CategoriesModel.query.order_by(CategoriesModel.order.asc()).all()
    return render_template('categorymanage.html',categories=categories)



@bp.route('/blogManager')
def blog_manager():
    blogs=BlogModel.query.filter_by(is_deleted=False).order_by(BlogModel.create_time.desc()).all()
    categories=CategoriesModel.query.all()
    return render_template('blogmanager.html',blogs=blogs,categories=categories)

@bp.route('/topicManager')
def topic_manager():
    topics=TopicModel.query.all()
    return render_template('topicmanage.html',topics=topics)


@bp.route('/editBlog/<int:blog_id>',methods=['GET'])
def edit_blog(blog_id):
    blog=BlogModel.query.get_or_404(blog_id)
    categories=CategoriesModel.query.all()
    return render_template('writeblog.html',blog=blog,categories=categories,user=g)

@bp.route('/searchBlog', methods=['GET', 'POST'])
@login_required
def search_blog():
    categories = CategoriesModel.query.all()  # 提前准备分类，GET/POST 都要用

    if request.method == 'POST':
        theme = request.form.get('theme', '').strip()
        statusb = request.form.get('statusblog', '').strip()
        categoryb = request.form.get('categoryblog', '').strip()
        search = request.form.get('search')
        if search == 'manager':
            queryblog = BlogModel.query.filter_by(author_id=g.user.id, is_deleted=False)

            if theme:
                queryblog = queryblog.filter(BlogModel.title.ilike(f'%{theme}%'))
            if statusb:
                queryblog = queryblog.filter_by(status=statusb)
            if categoryb:
                queryblog = queryblog.filter_by(categorie_id=int(categoryb))

            blogs = queryblog.order_by(BlogModel.create_time.desc()).all()
            return render_template('blogmanager.html', blogs=blogs, categories=categories)
        elif search == 'recyler':
            queryblog = BlogModel.query.filter_by(author_id=g.user.id, is_deleted=True)

            if theme:
                queryblog = queryblog.filter(BlogModel.title.ilike(f'%{theme}%'))
            if statusb:
                queryblog = queryblog.filter_by(status=statusb)
            if categoryb:
                queryblog = queryblog.filter_by(categorie_id=int(categoryb))

            blogs = queryblog.order_by(BlogModel.create_time.desc()).all()
            return render_template('recyler.html', blogs=blogs, categories=categories)

    # GET 请求也传入分类
    return render_template('blogmanager.html', categories=categories)


@bp.route('/deleteBlog/<int:blog_id>')
def delete_blog(blog_id):
    blog=BlogModel.query.get_or_404(blog_id)
    if blog.author_id!=g.user.id:
        return 'Not Permission！！！'
    blog.is_deleted=True
    db.session.commit()
    flash('该博客已经移入回收站','info')
    return redirect(url_for('security.blog_manager'))

# @bp.route('deleteCategory/<int:category_id>')疑似不需要删除分类的操作
# def delete_category(category_id):
#     category=CategoriesModel.query.get_or_404(category_id)
#     blog

@bp.route('/reback/<int:blog_id>')
def reback(blog_id):
    blog=BlogModel.query.get_or_404(blog_id)
    if blog.author_id!=g.user.id:
        return 'Not Permission！！！'
    blog.is_deleted=False
    db.session.commit()
    flash('该博客已经复原！！！','info')
    return redirect(url_for('security.recyler'))


@bp.route('/recyler')
def recyler():
    blogs=BlogModel.query.filter_by(is_deleted=True,author_id=g.user.id).all()
    return render_template('recyler.html',blogs=blogs)


@bp.route('/delete_permanently/<int:blog_id>')
def delete_parmanently(blog_id):
    # blog=BlogModel.query.filter_by(id=blog_id,author_id=g.user.id).first()
    blog=BlogModel.query.get_or_404(blog_id)
    if blog.author_id!=g.user.id:
        abort(403)
    db.session.delete(blog)
    db.session.commit()
    flash('该博客已永久删除！！！','danger')
    return redirect(url_for('security.recyler'))

@bp.route('/delete_all_parmanently')
def delete_all_parmanently():
    blogs=BlogModel.query.filter_by(is_deleted=True,author_id=g.user.id).all()
    for blog in blogs:
        delete_parmanently(blog.id)
    db.session.commit()
    flash('回收站已经全部清空！！！','danger')
    return redirect(url_for('security.recyler'))



